import { registerLogin } from '@/api/reception'
import { getToken, setToken, removeToken } from '@/utils/auth'
import { getName, setName, removeName } from '@/utils/auth'
import { getPhoto, setPhoto, removePhoto } from '@/utils/auth'

const state = {
  token: getToken(),
  name: getName,
  photo: getPhoto
}

const mutations = {
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_PHOTO: (state, photo) => {
    state.photo = photo
  }
}

const actions = {
  login({ commit }, userInfo) {
    const { username, password } = userInfo
    return new Promise((resolve, reject) => {
      registerLogin({ username: username.trim(), password: password }).then(response => {
        const { token, name, photo } = response.data
        commit('SET_TOKEN', token)
        commit('SET_NAME', name)
        commit('SET_PHOTO', photo)
        setToken(token)
        setName(name)
        setPhoto(photo)
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },
  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      commit('SET_TOKEN', '')
      commit('SET_NAME', '')
      commit('SET_PHOTO', '')
      removeToken()
      removeName()
      removePhoto()
      resolve()
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
